<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px' }">
      <div class="flex justify-between mb-2">
        <a-button type="primary" class="px-1.5" ghost @click="onclickList"><UnorderedListOutlined />患者列表</a-button>
        <!-- <a-button class="next-btn px-1.5">下一个</a-button>
        <div class="">
          <div class="number-btn over-btn text-xs">过号</div>
          <div class="number-btn recall-btn text-xs">复呼</div>
        </div>
        <a-button type="primary" class="px-1.5">结束就诊</a-button> -->
        <a-button :disabled="!store.isCallConfig" class="next-btn px-1.5" :loading="nextLoading" @click="clickNextNumber"> 下一个 </a-button>
        <div class="flex flex-col">
          <a-button :disabled="!store.isCallConfig" :loading="overLoading" size="small" class="number-btn over-btn text-xs" @click="clickOverNumber">
            过号
          </a-button>
          <a-button :disabled="!store.isCallConfig" :loading="againCallLoading" size="small" class="number-btn recall-btn text-xs" @click="clickAgainCall">
            复呼
          </a-button>
        </div>
        <a-button type="primary" :loading="endVisitLoading" class="px-1.5" @click="onEndVisit">结束就诊</a-button>
      </div>
      <PatientList ref="patientListRef" />
      <div v-if="getSystemConfig('IS_DOCTOR_ASSISTANT') === '1' && !isArmy" class="flex flex-wrap items-center pt-2">
        <a-form-item label="医助" class="w-full mb-0" :label-col="{ style: { width: '64px' } }">
          <SelectTable v-model:value="assistant1Emp.empName" type="员工" placeholder="请选择" @select="onSelectAssistant1" />
        </a-form-item>
      </div>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="patientData" :show-insurance="true" @change="onCaseSuccess()">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="" label="卡号" :width="140" :value="patientData?.brId" />
            <LabelValue class="" label="病案号" :width="140" :value="patientData[isBGMSG ? 'brBlkh' : 'oprSn']" />
            <LabelValue class="ml-4" label="科室" :width="140" :value="patientData?.ksmc" />
            <LabelValue class="ml-4" label="类别" :width="200" :value="patientData?.ghlb" />
            <!-- <LabelValue class="ml-4" label="过敏史" :width="280" :tooltip="true" :value="patientData?.brGms" /> -->
            <!-- <AllergyHistory class="ml-4" :width="280" :value="patientData.brGms" :patient-info="patientData" @success="(e) => (patientData.brGms = e)" /> -->
            <AllergyHistory class="ml-4" :width="280" :patient-info="patientData" />
          </div>
          <div class="flex items-center">
            <LabelValue class="" label="门诊号" :width="140" :value="patientData?.jzbh" />
            <LabelValue class="" label="病历号" :width="140" :value="patientData[isBGMSG ? 'oprSn' : 'brBlkh']" />
            <LabelValue class="ml-4" label=" 排队号" :width="140" :value="patientData?.lsh" />
            <LabelValue class="ml-4" :width="200" label="时间" :value="patientData?.ghsj" />
            <LabelValue v-if="!isArmy" class="ml-4" :width="200" label="关注项目" :value="patientData?.gzxmmc" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-auto" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <a-tabs
            v-model:active-key="activeKey"
            destroy-inactive-tab-pane
            :class="store.currentPatient?.jzbh ? 'h-full' : 'tabs-disabled h-full'"
            @change="onChangeTabs"
          >
            <a-tab-pane key="1" tab="病历">
              <component :is="getAsyncComponent('TabCase')" :case-data="patientData" :active-key="activeKey" @success="onCaseSuccess" />
            </a-tab-pane>
            <a-tab-pane v-if="getSystemConfig('IS_OUTP_OPHTH_SPECIALTY_EMR') === '1'" key="0" tab="电子病历">
              <component :is="getAsyncComponent('EMedicalRecord')" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_治疗方案 -->
            <a-tab-pane v-if="systemConfig.isTreatment && !isArmy" key="1001" tab="治疗方案">
              <iframe :src="getPACSUrl('dlgEditZLFA')" width="100%" height="100%" frameborder="0"></iframe>
            </a-tab-pane>
            <a-tab-pane v-if="systemConfig.isMedicine" key="2" tab="医嘱">
              <component :is="getAsyncComponent('TabDoctorAdvice')" :active-key="activeKey" />
            </a-tab-pane>
            <a-tab-pane v-if="!systemConfig.isMedicine" key="3" tab="处置">
              <component :is="getAsyncComponent('TabDispose')" />
            </a-tab-pane>
            <a-tab-pane v-if="!systemConfig.isMedicine" key="4" tab="西成药" :disabled="!isHasDiagnosis && systemConfig.isWestMedicine">
              <component :is="getAsyncComponent('TabWesternMedicine')" />
            </a-tab-pane>
            <a-tab-pane v-if="!systemConfig.isCirculation" key="16" tab="流转处方">
              <component :is="getAsyncComponent('TabPrescriptionCirculation')" />
            </a-tab-pane>
            <a-tab-pane v-if="getSystemConfig('IS_OUTP__DOCTOR_OOS_ADVICE') === '1'" key="14" tab="视光医嘱">
              <component :is="getAsyncComponent('TabOptician')" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_中草药 -->
            <a-tab-pane v-if="systemConfig.isCentreMedicine && !isArmy" key="5" tab="中草药" :disabled="!isHasDiagnosis">
              <component :is="getAsyncComponent('TabTCM')" :jzbh="store.currentPatient.jzbh" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_特检报告 -->
            <a-tab-pane v-if="systemConfig.isReport && !isArmy" key="1003" tab="特检报告">
              <iframe :src="getPACSUrl('dlgTJJCxm', true)" width="100%" height="100%" frameborder="0"></iframe>
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_验光试戴确认-->
            <a-tab-pane v-if="systemConfig.isOptometry && dynamicConfig.bqmc === '验光试戴确认'" key="1007" tab="验光试戴确认">
              <iframe :src="dynamicConfig.url" width="100%" height="100%" frameborder="0"></iframe>
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_检查 -->
            <!-- <a-tab-pane v-if="systemConfig.isInspect" key="6" tab="检查">
              <component :is="getAsyncComponent('TabCheck')" />
            </a-tab-pane> -->
            <!-- 是否启用门诊医生工作站子频道_检验 -->
            <a-tab-pane v-if="systemConfig.isInspection" key="7" tab="检验">
              <component :is="getAsyncComponent('TabLaboratory')" :patient-data="patientData" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_医技 -->
            <a-tab-pane v-if="systemConfig.isInspect" key="8" tab="医技">
              <component :is="getAsyncComponent('TabTechnology')" :patient-data="patientData" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_屈光手术 -->
            <a-tab-pane v-if="systemConfig.isRefractiveSurgery" key="9" tab="屈光手术">
              <component :is="getAsyncComponent('TabOperation')" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_手术 -->
            <a-tab-pane v-if="systemConfig.isOperation" key="801" tab="手术">
              <TabOperationIn :is="getAsyncComponent('TabOperation')" :jzbh="store.currentPatient.jzbh" :br-id="store.currentPatient.brId" is-out-doctor />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_入院申请 -->
            <a-tab-pane v-if="systemConfig.isApplication" key="10" tab="入院申请">
              <component :is="getAsyncComponent('TabHospitalApply')" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_手术文书 -->
            <a-tab-pane v-if="systemConfig.isDocument" key="1004" tab="手术文书">
              <iframe :src="getPACSUrl('dlgXZZQTYS', true)" width="100%" height="100%" frameborder="0"></iframe>
            </a-tab-pane>
            <a-tab-pane key="11" tab="证明书">
              <component :is="getAsyncComponent('TabCertificate')" />
            </a-tab-pane>

            <a-tab-pane v-if="isDev" key="13" tab="医疗影像">
              <component :is="getAsyncComponent('DICOM')" />
            </a-tab-pane>
            <a-tab-pane v-if="getSystemConfig('IS_OUTP__DOCTOR_KEEP_IN_HOSPITAL') === '1'" key="15" tab="留观">
              <component :is="getAsyncComponent('StaySee')" />
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <SideHistory :key="activeKey" :active-key="activeKey" @copy="onCopySuccess" />
      </div>
    </div>
    <PatientTableModal v-model:open="registrationOpen" @select="onSelectRow" />
    <!--危急值 -->
    <DoctorCrisisModal />
  </div>
</template>

<script setup>
import { nextTick, ref, watch, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { UnorderedListOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import useUserStore from '@/store/user'
import DoctorCrisisModal from '@/views/workstation-inspect/workstation/components/DoctorCrisisModal/index.vue'

import TabOperationIn from '@/views/in-doctor/workstation/components/TabOperation'
import useStore from '../store'
// import DICOM from './DICOM'
// import TabTCM from './TabTCM'
// import TabCase from './TabCase'
// import StaySee from './StaySee'
// import TabCheck from './TabCheck'
// import TabDispose from './TabDispose'
// import TabOperation from './TabOperation'
// import TabLaboratory from './TabLaboratory'
// import EMedicalRecord from './EMedicalRecord'
// import TabCertificate from './TabCertificate'
// import TabDoctorAdvice from './TabDoctorAdvice'
// import TabHospitalApply from './TabHospitalApply'
// import TabWesternMedicine from './TabWesternMedicine'

import SideHistory from './components/SideHistory'
import PatientList from './components/PatientList'
// import HistoryCase from './components/HistoryCase'
// import HistoryPart from './components/HistoryPart'
// import CommonlyUsed from './components/CommonlyUsed.vue'
import PatientTableModal from './components/PatientTableModal'

const modules = import.meta.glob('./**/index.vue')

const getAsyncComponent = (component) => {
  return defineAsyncComponent(modules[`./${component}/index.vue`])
}

const router = useRouter()
const store = useStore()
const patientListRef = ref()
const activeKey = ref(router.currentRoute.value.query.tab || '1')
// const leftActiveKey = ref('1')
// const activeKeyPart = ref('1')
const isHasDiagnosis = ref(false)
const registrationOpen = ref(false)
const systemConfig = {
  isTreatment: getSystemConfig('IS_OUTP_OPHTH_TREATMENT_PIAN') === '1', //治疗方案
  isMedicine: getSystemConfig('ENABLE_OUTP__SINGLE_ADVICEORDER_MODE') === '1', //0处置、西成药1医嘱
  isWestMedicine: getSystemConfig('ISSUE_DRUG_ORDER_WITHOUT_ICD10') === '0', // 西成药
  isCentreMedicine: getSystemConfig('IS_OUTP__DOCTOR_TCM') === '1', // 中草药
  isReport: getSystemConfig('IS_OUTP_OPHTH_SPECIAL_EXAMINATION') === '1', // 特检报告
  isOptometry: getSystemConfig('IS_OUTP_OPHTH_TRY_OPTOMETRY') === '1', // 验光试戴确认
  isInspect: getSystemConfig('IS_OUTP__DOCTOR_RIS') === '1', // 检查
  isInspection: getSystemConfig('IS_OUTP__DOCTOR_LIS') === '1', // 检验
  isOperation: getSystemConfig('IS_OUTP__DOCTOR_OPERATION') === '1', // 手术
  isRefractiveSurgery: getSystemConfig('IS_OUTP_DOCTOR_LASIK_OPERATION') === '1', //   屈光手术
  isApplication: getSystemConfig('IS_OUTP__DOCTOR_INP') === '1', // 入院申请
  isDocument: getSystemConfig('IS_OUTP__DOCTOR_OPERATION_DOCUMENT') === '1', // 手术文书
  isOptician: getSystemConfig('IS_OUTP_DOCTOR_OOS_ADVICE') === '1', // 视光医嘱
  isCirculation: getSystemConfig('IS_OUTP_DOCTOR_PRESCRIPTION_CIRCULATION') === '1' // 流转处方
}
const onclickList = () => {
  registrationOpen.value = true
}
const patientData = ref({})
const getData = async (jzbh) => {
  if (!jzbh) return
  const { code, msg, data } = await post('/outp/mzys/getOutpRecordInfo', {
    mzjlbh: jzbh
  })
  if (code !== 0) return message.error(msg || '获取病历信息失败')
  // patientData.value =
  //   {
  //     ...data,
  //     assistant1EmpId: data.assistant1EmpId ?? patientData.value?.assistant1EmpId,
  //     assistant1EmpName: data.assistant1EmpName ?? patientData.value?.assistant1EmpName
  //   } || {}
  patientData.value = data
  // if (!data?.assistant1EmpId && patientData.value?.assistant1EmpId && getSystemConfig('IS_DOCTOR_ASSISTANT') === '1') {
  //   onSelectAssistant1({ empId: patientData.value?.assistant1EmpId, empName: patientData.value?.assistant1EmpName }, true)
  // }
  if (patientData.value?.bcLczdZdmc) {
    isHasDiagnosis.value = true
  } else {
    isHasDiagnosis.value = false
  }
}

const onCaseSuccess = () => {
  getData(store.currentPatient.jzbh)
  isHasDiagnosis.value = true
  patientListRef.value?.queryList(false)
}
const onSelectRow = (row) => {
  patientListRef.value.onSelect(row)
}
const onCopySuccess = () => {
  patientListRef.value?.queryList(false)
}
const assistant1Emp = ref({})
const onSelectAssistant1 = async (select, type) => {
  // patientData.value.assistant1EmpId = select.empId
  // patientData.value.assistant1EmpName = select.empName
  assistant1Emp.value = select
  if (!patientData.value.jzbh) return
  const { code, msg } = await post(`outp/mzys/upAssistant`, { assistant1EmpId: select.empId, jzbh: patientData.value.jzbh })
  if (code !== 0) return message.error(msg || '失败')
  if (!type) {
    message.success('操作成功')
  }
}

const { empId } = useUserStore()
const host = getSystemConfig('HIS_MEDICAL_RECORD_URL') //跳转病历系统地址
const setbh = getSystemConfig('ORGNIZATION_CODE') //组织机构代码
const yqbh = getSystemConfig('OUTP_OPHTH_INSTRUMENT_BH') //仪器编号

const getPACSUrl = (view, isYqflg = false, isYqbh = false) => {
  let url = `${host}/Ajax/CS_Result?page=${view}&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`
  isYqflg && (url += `&yqflg=1`)
  isYqbh && (url += `&yqbh=${yqbh}`)
  return url
}
const dynamicConfig = ref({})
const getDynamicUrl = async () => {
  if (!store.currentPatient.jzbh) return
  const { data, code } = await post(`${host}/Ajax/getZLFA_BQB_JZBH?jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`)
  if (code === '0' && data[0]) {
    data[0].url = `${host}/Ajax/CS_Result?page=${data[0].url}&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`
    dynamicConfig.value = data[0]
  }
}
// 下一个
const nextLoading = ref(false)
const clickTimeInfo = {
  nextBtn: 0,
  overBtn: 0,
  againBtn: 0,
  endBtn: 0
}

const clickNextNumber = async () => {
  const timer = new Date().getTime()
  if (timer - clickTimeInfo.nextBtn < 15000) return message.warning('15秒内不能连续点击')
  clickTimeInfo.nextBtn = timer
  if (store.callConfigData.jzbh) {
    nextLoading.value = true
    const { code, msg, data } = await post(`/outp/doctorQueue/doCallNext`, { QueueId: store.callConfigData.queueId })
    nextLoading.value = false
    if (code !== 0) return message.error(msg || '操作失败')
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(data)) //调用winform叫号
  } else {
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
  }
}
// 过号
const overLoading = ref(false)
const clickOverNumber = async () => {
  if (store.callConfigData.jzbh) {
    overLoading.value = true
    const { code, msg, data } = await post(`/outp/doctorQueue/doSkip`, { QueueId: store.callConfigData.queueId })
    overLoading.value = false
    if (code !== 0) return message.error(msg || '操作失败')
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(data)) //调用winform叫号
  } else {
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
  }
}
const againCallLoading = ref(false)
const clickAgainCall = async () => {
  if (store.callConfigData.jzbh) {
    againCallLoading.value = true
    const { code, msg, data } = await post(`/outp/doctorQueue/doCallChosen`, { QueueId: store.callConfigData.queueId })
    againCallLoading.value = false
    if (code !== 0) return message.error(msg || '操作失败')
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(data)) //调用winform叫号
  } else {
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
  }
}
// 结束就诊
const endVisitLoading = ref(false)
const onEndVisit = async () => {
  if (!store.isCallConfig) {
    endVisitLoading.value = true
    const { code, msg } = await post(`/outp/mzys/modifyPatientClinicStatus`, {
      // qmQrId: store.currentPatient.qmQrId,
      ghzt: 3,
      jzbh: store.currentPatient.jzbh,
      ysbh: empId
    })
    endVisitLoading.value = false
    if (code !== 0) return message.error(msg || '操作失败')
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
    return
  }
  const timer = new Date().getTime()
  if (timer - clickTimeInfo.endBtn < 15000) return message.warning('15秒内不能连续点击')
  clickTimeInfo.endBtn = timer
  if (store.callConfigData.jzbh) {
    endVisitLoading.value = true
    const { code, msg, data } = await post(`/outp/mzys/modifyPatientClinicStatus`, {
      // qmQrId: store.currentPatient.qmQrId,
      ghzt: 3,
      jzbh: store.callConfigData.jzbh,
      ysbh: store.callConfigData.ysbh ? store.callConfigData.ysbh : ''
    })
    endVisitLoading.value = false
    if (code !== 0) return message.error(msg || '操作失败')
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
    window.openExe?.callUpdSend(JSON.stringify(data)) //调用winform叫号
  } else {
    patientListRef.value?.queryList(true)
    patientListRef.value?.getRegistereCount()
  }
}
// const getCallConfig = async () => {
//   const { code, data, msg } = await post(`/outp/dictQueue/checkCallNumberConfig`, {})
//   if (code !== 0) return message.error(msg || '获取叫号配置失败')
//   store.isCallConfig = data
// }

window.addEventListener('message', (event) => {
  event.data === 'reloadHisTab' && getDynamicUrl()
})
const isDev = import.meta.env.DEV
//切换Tab标签
const onChangeTabs = () => {
  if (isDev) {
    router.push({
      path: router.currentRoute.value.path,
      query: {
        tab: activeKey.value
      }
    })
  }
}
watch(
  () => store.isRefreshPatientList,
  (val) => {
    val && patientListRef.value?.queryList(false)
  }
)
watch(
  () => store.currentPatient.jzbh,
  (val) => {
    if (val) {
      getData(val)
      systemConfig.isOptometry && getDynamicUrl()
    } else {
      patientData.value = {}
    }
    activeKey.value = '1'
    if (isDev && val) {
      nextTick(() => {
        activeKey.value = router.currentRoute.value.query.tab || '1'
      })
    }
  },
  { immediate: true }
)
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
watch(
  () => activeKey.value,
  (val) => {
    if (val === '1') {
      getData(store.currentPatient.jzbh)
    }
  }
)
onUnmounted(() => {
  // store.callConfigData = {}
  // store.currentPatient = {}
})
onMounted(() => {
  store.currentPatient?.jzbh && patientListRef.value.onSelect(store.currentPatient)
})
</script>
<style lang="less" scoped>
:deep(.ant-tabs-tab) {
  padding: 12px 24px;
}
.tabs-disabled {
  cursor: not-allowed;
  filter: opacity(0.5);
  pointer-events: none;
}
:deep(.ant-tabs-content) {
  height: calc(100% - 8px);
}

// .history-expand {
//   width: 76px !important;
//   :deep(.ant-tabs) {
//     visibility: hidden;
//   }
// }
// .history-expand-btn {
//   padding: 8px;
//   color: var(--primary-color);
//   background-color: var(--secondary-color);
//   border-radius: 8px;
//   cursor: pointer;
// }

.next-btn {
  color: #fff;
  background-color: #369c17;
  border: 1px solid #369c17;
  &:hover {
    color: #fff;
    background-color: #369c17dd;
  }
  &:disabled {
    cursor: not-allowed;
    filter: opacity(0.5);
  }
}
.number-btn {
  height: 16px !important;
  padding: 0px 16px !important;
  border: none !important;
  border-radius: 0px !important;
  &:disabled {
    cursor: not-allowed;
    filter: opacity(0.5);
  }
}
.over-btn {
  display: block;
  color: #fff;
  background-color: #db6564;
  cursor: pointer;
  &:hover {
    color: #fff;
  }
  &:disabled {
    cursor: not-allowed;
    filter: opacity(0.5);
  }
}
.recall-btn {
  margin-bottom: 4px !important;
  color: #fff;
  background-color: #ff8d03;
  cursor: pointer;
  &:hover {
    color: #fff;
  }
  &:disabled {
    cursor: not-allowed;
    filter: opacity(0.5);
  }
}
</style>
